package org.watchrecords;

import org.apache.wicket.Request;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authorization.strategies.role.Roles;

import org.watchrecords.constants.Permission;
import org.watchrecords.dbo.User;
import org.watchrecords.managers.UserManager;

import com.google.inject.Inject;

public class WatchRecordsSession extends AuthenticatedWebSession {
    /**
     * 
     */
    private static final long serialVersionUID = 8443977352646119535L;
    @Inject private static UserManager securityManager;

    public WatchRecordsSession(Request request) {
        super(request);
    }

    @Override
    public boolean authenticate(String username, String password) {
        User user = securityManager.getUser(username, password);
        
        if (user != null) {
            setAttribute("userId", user.getId());
            return true;
        }
        else {
            return false;
        }
    }
    
    public User getUser() {
        Integer id = (Integer) getAttribute("userId");
        
        return id == null ? null : securityManager.getUser(id);
    }
    
    public boolean haveAnyPermission(Permission... perms) {
        User user = getUser();
        
        return user == null ? false : user.getRole().haveAnyPermission(perms);
    }

    @Override
    public Roles getRoles() {
        return new Roles(getUser().getRole().toString());
    }
    
    @Override
    public void signOut() {
        this.invalidate();
    }
}
